import React, { useState } from 'react';
import { withRouter } from 'react-router-dom';
import './index.css';
import Header from "../../components/Header/Header"
import Footer from "../../components/Footer/Foot"
import {Tabs, Upload, message, Collapse } from 'antd';
import {evidenceCheck, txidCheck} from "@/utils/api";
import {connect} from "react-redux";
import {
    ArrowLeftOutlined
} from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import ReactJson from 'react-json-view'

const { TabPane } = Tabs;
const { Panel } = Collapse;


interface IState {
    path: string,
    isShow: boolean,
    t_id:string,
    checkData: {
        "Title": {
            "title": string,
            "founder": string,
        },
        "owner": string,
        "document_hash": string
    },
    lineItem: {
        number: string,
        currentBlockHash:string,
        previousBlockHash:string,
        transactions: any,
        timestamp: number
    },
    verification: number
}

interface IProps {
    match:any
}

class Evidence extends React.Component<IProps, IState> {
    formRef:any = React.createRef<FormInstance>();
    constructor(props: any) {
        super(props);
        this.state = {
            path: "",
            isShow: false,
            t_id:'',
            lineItem: {
                number: "",
                currentBlockHash:"",
                previousBlockHash:"",
                transactions: [],
                timestamp: 0
            },
            checkData: {
                "Title": {
                    "title": "",
                    "founder": "",
                },
                "owner": "",
                "document_hash": ""
            },
            verification:1
        }
        sessionStorage.setItem("path", this.props.match.path)

    }


    evidenceCheck = () => {
        if(this.state.path == "") {
            message.warn({
                content: '文件不能为空',
                className: 'custom-class',
                style: {
                    marginTop: '30vh',
                },
            })
            return;
        }
        evidenceCheck(
            {
                "file_path": this.state.path
            }
        )
            .then((res: any) => {
                if(res.data.code == 0) {
                    message.success("查询成功")
                    this.setState({
                        isShow: true,
                        checkData: res.data.data
                    })

                }else {
                    console.log(res)
                    message.warn(res.data.msg)
                    // this.setState({
                    //     isShow: true
                    // })

                }
            })
            .catch((error: any) => {
                message.error(error);
            })
    }

    formateDate(datetime:any) {
        // let  = "2019-11-06T16:00:00.000Z"
        function addDateZero(num:any) {
            return (num < 10 ? "0" + num : num);
        }
        let d = new Date(datetime);
        let formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate()) + ' ' + addDateZero(d.getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds());

        return formatdatetime;
    }


    jsonTop = (e:any) => {
        // e['created'] = this.getYMDHMS(e['created'])
        let index=e.lastIndexOf("value=");
        e=e.substring(index+6);
        e = JSON.parse(e)
        e['created'] = this.formateDate(e['created'])
        return e
    }


    txidCheck = () => {
        if(this.state.t_id == "") {
            message.warn({
                content: '验证编码不能为空',
                className: 'custom-class',
                style: {
                    marginTop: '30vh',
                },
            })
            return;
        }
        txidCheck(this.state.t_id
        )
            .then((res: any) => {
                console.log(res.data.code)
                if(res.data.code == 0) {
                    message.success({
                        content: '查询成功',
                        className: 'custom-class',
                        style: {
                            marginTop: '30vh',
                        },
                    })
                    this.setState({
                        isShow: true,
                        lineItem: res.data.data
                    })

                }else {
                    message.error({
                        content: '验证失败，无法匹配到与链上一致的信息，请核对上传文件',
                        className: 'custom-class',
                        style: {
                            marginTop: '30vh',
                        },
                    });
                    // this.setState({
                    //     isShow: true
                    // })
                }
            })
            .catch((error: any) => {
                message.error(error);
            })
    }

    inputChange = (e:any) =>{
        this.setState({
            t_id:e.target.value
        })
    }
    getYMDHMS (timestamp: any) {
        let time:any = new Date(timestamp*1000)
        return time.toLocaleDateString().replace(/\//g, "-") + " " + time.toTimeString().substr(0, 8)
    }
    callback = () => {
        this.setState({
            isShow: false,
            lineItem: {
                number: "",
                currentBlockHash:"",
                previousBlockHash:"",
                transactions: [],
                timestamp: 0
            }
        })
    }

    onChange = (info:any) => {
        if (info.file.status !== 'uploading') {

            this.setState({
                path: info.file.response.data
            })
            console.log(this.state.path)
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name}上传成功`);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败`);
        }
    }

    render () {
        const {  path , isShow, lineItem, verification} = this.state;
        return (

            <div>
                <div className="boxEvidence">
                    <Header></Header>
                    <div className="app-query">
                        <div className="query_auto">
                            <div className="query_top">
                                <div className="left">
                                    <div className="left_top">
                                        <span className="line"></span>
                                        <span>科学论文证据链证据查询</span>
                                        <span className="but">温馨提示</span>
                                    </div>
                                    <div className="text"><span>1</span>原始证据保平安，区块的数据结构保证科研材料的原始性</div>
                                    <div className="text"><span>2</span>数据资产的确权，证据材料的所有权由科研网络进行共识</div>
                                    <div className="text"><span>3</span>细粒度访问控制，利用智能合约定制数据资产的共享方式</div>
                                </div>
                                <img src={require("../../assets/img/tu.png")} alt="" />
                            </div>
                            <div className="query_bu">
                                <div className="but"><span onClick={()=> {
                                    this.setState({
                                        isShow:false,
                                        verification: 1
                                    })
                                }}>证据包验证</span><span  onClick={()=> {
                                    this.setState({
                                        isShow:false,
                                        verification: 2
                                    })
                                }}>编号验证</span></div>
                                {
                                    this.state.verification == 1 ?
                                        <div className="input">
                                            <input type="text" placeholder="证据包上传" value={ path }/>
                                        <div className="upload">
                                            <Upload showUploadList={false} onChange={this.onChange}  name = 'file' action = '/apiCode/api/evidence/upload'>
                                                <img src={require("../../assets/img/inputImg.png")} alt="" />
                                                <span>选择文件</span>
                                            </Upload>
                                        </div>
                                        <span onClick={this.evidenceCheck}>查询验证</span>
                                        </div> :
                                        <div className="input">
                                            <input type="text" placeholder="证书编号"  ref='username' onChange={(e)=>this.inputChange(e)}/>
                                        <span onClick={this.txidCheck} >查询验证</span>
                                        </div>
                                }
                            </div>
                            {
                                (lineItem.transactions.length && this.state.verification == 2) ? <div className="table">
                                    <div className="h5">
                                        <span className="tab1">创建者</span>
                                        <span className="tab2">类型</span>
                                        <span className="tab3">存证时间</span>
                                        <span className="tab4">状态</span>
                                        <span className="tab5">证据编号</span>

                                    </div>
                                    {
                                        lineItem.transactions.map((item: any,index: any)=>{
                                            return(
                                                <Collapse accordion>
                                                    <Panel header={ <div className="h6">
                                                        <span className="tab1">{item.subject}</span>
                                                        <span className="tab2">{item.type}</span>
                                                        <span  className="tab3">{this.getYMDHMS(item.timestamp)}</span>
                                                        <span className="tab4">{item.status}</span>
                                                        <span className="tab5"  style={{fontSize:'12px'}}>{item.txid}</span>
                                                    </div>} key="1">
                                                        {

                                                            item.actions  != null && item.actions[0].rwSet.length ?item.actions[0].rwSet[0].wSet.map((e:any) => {
                                                                // @ts-ignore
                                                                return <div style={{textAlign:'left'}}>
                                                                    <ReactJson src={this.jsonTop(e)} name={"上链数据"}/>
                                                                  </div>
                                                            }): null
                                                        }
                                                    </Panel>
                                                </Collapse>
                                            )
                                        })
                                    }
                                </div> : (this.state.checkData && this.state.verification == 1 && this.state.isShow) ? <div className="table">
                                    <div className="h5">
                                        <span style={{width: '30%'}}>标题</span>
                                        <span  style={{width: '15%'}}>
                      创建者</span>
                                        <span style={{width: '15%'}}>所有者</span>
                                        <span  style={{width: '40%'}}>document_hash</span>

                                    </div>
                                    <div  style={{display: 'flex', padding:'5px'}}>
                                        <span  style={{width: '30%'}}>{this.state.checkData.Title.title}</span>
                                        <span  style={{width: '12.5%'}}>{this.state.checkData.Title.founder}</span>
                                        <span   style={{width: '12.5%'}}>{this.state.checkData.owner}</span>
                                        <span style={{width: '45%'}}>{this.state.checkData.document_hash}</span>
                                    </div>
                                </div>: null
                            }

                        </div>
                    </div>
                    <Footer></Footer>
                </div>
            </div>

        )
    }
}


export default withRouter(connect((state: any) => state.user, {  evidenceCheck, txidCheck })(Evidence))


